#!/bin/sh

if [ -z "$TIME" ] ; then
	[ `uname -s` = "Darwin" ] && TIME=gtime || TIME=time
fi

[ "$1" = "--save" ] && shift && SAVE="$1" && shift

[ "$NB" ] || NB=10
[ "$LIM" ] || LIM=1.0
[ "$TAG" ] || TAG="$*"

i=0
F=`mktemp -t timings` 

echo "- Running $NB x \"$*\"" >&2
while [ $i -lt $NB ] ; do
	echo "-- Run $i" >&2
	$TIME -a -o $F --format="%U %S $TAG" $* >&2
	i=$((i + 1))
done
gawk -f - -- $F << EOF 
{
	if((\$1+0) >= $LIM)
	{
		c ++; s += \$1 ; ss+=\$2 ;
		if(c == 1 || \$1 <= m) { m = \$1; ms = \$2 } ;
		if(c == 1 || \$1 >= ma) { ma = \$1; mas = \$2 };
	}
}
END {
  if(c > 2) { pm = (s - m - ma) / (c - 2) };
	if(c > 2) { pma = (s + ss - m - ms - ma - mas ) / (c - 2) };
	print s / c ";" (s + ss) / c ";" pm ";" pma ";" m ";" ms ";" ma ";" mas ";" c ";$TAG" ;
}
EOF

[ "$SAVE" ] && cat $F | gawk '{ if(($1+0) > 1.0) print($0); }' > $SAVE
rm $F
